<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="设备名称" prop="name"  class="item">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入设备名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="规格/型号" prop="model"  class="item">
        <el-input
          v-model="queryParams.model"
          placeholder="请输入规格型号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="编号" prop="code" class="item">
        <el-input
          v-model="queryParams.code"
          placeholder="请输入编号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="使用状态" prop="useState" class="item">
        <el-select v-model="queryParams.useState" placeholder="请选择使用状态" clearable size="small">
          <el-option
            v-for="dict in useStateOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="购置年份" prop="buyYear" class="item">
        <el-date-picker clearable size="small" style="width: 200px"
          v-model="queryParams.buyYear"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="选择购置年份">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="检测时间" prop="checkTime" class="item">
        <el-date-picker clearable size="small" style="width: 200px"
          v-model="queryParams.checkTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="选择检测时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['experiment:equipment:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['experiment:equipment:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['experiment:equipment:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" icon="el-icon-upload2" size="mini" @click="handleImport" v-hasPermi="['experiment:equipment:import']">导入</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['experiment:equipment:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="multiple"
          @click="handleChangeState"
          v-hasPermi="['experiment:equipment:state']"
        >完好</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-edit"
          size="mini"
          :disabled="multiple"
          @click="handleChangeRepairState"
          v-hasPermi="['experiment:equipment:repair']"
        >维修</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-edit"
          size="mini"
          :disabled="multiple"
          @click="handleChangeForbidState"
          v-hasPermi="['experiment:equipment:forbid']"
        >禁用</el-button>
      </el-col>
	  <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar> 
    </el-row>

    <el-table v-loading="loading" :data="equipmentList" @selection-change="handleSelectionChange" border :row-class-name="tableRowClassName" style="width: 100%"
    height="600">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="主键ID" align="center" prop="equipmentId" v-if="false"/>
      <el-table-column label="设备名称" align="center" prop="name" fixed/>
      <el-table-column label="规格/型号" align="center" prop="model" />
      <el-table-column label="编号" align="center" prop="code" />
      <el-table-column label="使用状态" align="center" prop="useState"  :formatter="useStateFormat" />
      <el-table-column label="购置年份" align="center" prop="buyYear" width="120" >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.buyYear, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="检测时间" align="center" prop="checkTime" width="120" >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.checkTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="明细" align="center" prop="detail" width="400"/>
      <el-table-column label="功能描述" align="center" prop="functionName" width="200"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleRepairDetail(scope.row)"
            v-hasPermi="['experiment:equipment:repairlist']"
          >维修记录</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['experiment:equipment:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['experiment:equipment:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改试验设备\计量设备信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="设备名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入设备名称" />
        </el-form-item>
        <el-form-item label="规格/型号" prop="model">
          <el-input v-model="form.model" placeholder="请输入规格型号" />
        </el-form-item>
        <el-form-item label="编号" prop="code">
          <el-input v-model="form.code" placeholder="请输入编号" />
        </el-form-item>
        <el-form-item label="购置年份" prop="buyYear">
          <el-date-picker clearable size="small" style="width: 200px"
            v-model="form.buyYear"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择购置年份">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="检测时间" prop="checkTime">
          <el-date-picker clearable size="small" style="width: 200px"
            v-model="form.checkTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择检测时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="明细" prop="detail">
          <el-input v-model="form.detail" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="功能描述" prop="functionName">
          <el-input v-model="form.functionName" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="使用状态">
          <el-radio-group v-model="form.useState">
            <el-radio
              v-for="dict in useStateOptions"
              :key="dict.dictValue"
              :label="parseInt(dict.dictValue)"
            >{{dict.dictLabel}}</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
     <!-- 导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body :close-on-click-modal="false">
      <el-upload ref="upload" :limit="1" accept=".xlsx, .xls" :headers="upload.headers" :action="upload.url + '?updateSupport=' + upload.updateSupport" :disabled="upload.isUploading" :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <div class="el-upload__tip" slot="tip">
          <el-checkbox v-model="upload.updateSupport" />是否更新已经存在的数据
          <el-link type="info" style="font-size:12px" @click="importTemplate">下载模板</el-link>
        </div>
        <div class="el-upload__tip" style="color:red" slot="tip">提示：仅允许导入“xls”或“xlsx”格式文件！</div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 添加或修改维修信息对话框 -->
    <el-dialog :title="repair.title" :visible.sync="repair.open" width="600px" append-to-body :close-on-click-modal="false">
      <el-form ref="repairForm" :model="repair.form" :rules="repair.rules" label-width="90px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="关联ID" prop="relIds"  v-if="false">
              <el-input v-model="repair.form.relIds" placeholder="请输入关联ID" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="表名" prop="tableName" v-if="false">
              <el-input v-model="repair.form.tableName" placeholder="请输入表名" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="维修时限" prop="repairDaterange">
              <el-date-picker
                  v-model="repair.form.repairDaterange"
                  size="medium"
                  name="se"
                  style="width: 350px"
                  value-format="yyyy-MM-dd"
                  type="daterange"
                  range-separator="-"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="19">
            <el-form-item label="维修内容" prop="content">
              <el-input v-model="repair.form.content"  show-word-limit  type="textarea" placeholder="请输入维修内容" maxlength="800" 
             />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitRepairForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 查看维修信息对话框 -->
    <el-dialog :title="repairDetail.title" :visible.sync="repairDetail.open" width="800px" append-to-body>
        <el-table v-loading="loading" :data="repairDetail.repairList" @selection-change="handleSelectionChange">
          <el-table-column label="开始时间" align="center" prop="startTime" width="180">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.startTime, '{y}-{m}-{d}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="结束时间" align="center" prop="finishTime" width="180">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.finishTime, '{y}-{m}-{d}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="维修内容" align="center" prop="content" />
      </el-table>
    </el-dialog>
  </div>
</template>

<script>
import { listEquipment, getEquipment, delEquipment, addEquipment, updateEquipment, exportEquipment ,importTemplate, changeState, addRepair, listRepair} from "@/api/experiment/equipment";
import { getToken } from "@/utils/auth";
export default {
  name: "Equipment",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 试验设备\计量设备信息表格数据
      equipmentList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 使用状态字典
      useStateOptions: [],
      //导入参数
      upload: {
        // 是否显示弹出层（导入）
        open: false,
        // 弹出层标题（导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/experiment/equipment/importData",
      },
      //维修内容
      repair: {
        // 是否显示弹出层（导入）
        open: false,
        // 弹出层标题（导入）
        title: "",
        //维修表单
        form:{
          relIds: null,
          tableName: 0,
          startTime: null,
          finishTime: null,
          content: null,
          repairDaterange: []
        },
        rules: {
            content: [
              { required: true, message: "维修内容不能为空", trigger: "blur" }
            ],
            repairDaterange: [
              {
                type: 'array',
                required: true,
                message: '请选择日期区间',
                fields: {
                  //tpye类型试情况而定,所以如果返回的是date就改成date
                  0: { type: 'string', required: true, message: '请选择开始日期' },
                  1: { type: 'string', required: true, message: '请选择结束日期' }
                }
              }
            ]
        }
      },
      //维修详情
      repairDetail: {
        // 是否显示弹出层（导入）
        open: false,
        // 弹出层标题（导入）
        title: "",
        //维修表单
        repairList: [],
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          relId: null,
          tableName: null,
          startTime: null,
          finishTime: null,
          relFinishTime: null,
          content: null
        },
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        model: null,
        code: null,
        useState: null,
        buyYear: null,
        checkTime: null,
      },
      // 表单参数
      form: {
        
      },
      // 表单校验
      rules: {
      }
    };
  },
  created() {
    this.getList();
    this.getDicts("experiment_use_state").then(response => {
      this.useStateOptions = response.data;
    });
  },
  methods: {
    /** 查询试验设备\计量设备信息列表 */
    getList() {
      this.loading = true;
      listEquipment(this.queryParams).then(response => {
        this.equipmentList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 使用状态字典翻译
    useStateFormat(row, column) {
      return this.selectDictLabel(this.useStateOptions, row.useState);
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.repair.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        equipmentId: null,
        name: null,
        model: null,
        functionName: null,
        code: null,
        useState: 0,
        buyYear: null,
        checkTime: null,
        detail: null
      };
      this.repair.form = {
          relIds: null,
          tableName: 0,
          startTime: null,
          finishTime: null,
          content: null
      };
      this.resetForm("repairForm");
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.equipmentId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加试验设备\计量设备信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const equipmentId = row.equipmentId || this.ids
      getEquipment(equipmentId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改试验设备\计量设备信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.equipmentId != null) {
            updateEquipment(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              }
            });
          } else {
            addEquipment(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              }
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const equipmentIds = row.equipmentId || this.ids;
      this.$confirm('是否确认删除试验设备\计量设备信息编号为"' + equipmentIds + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delEquipment(equipmentIds);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(function() {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有试验设备\计量设备信息数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportEquipment(queryParams);
        }).then(response => {
          this.download(response.msg);
        }).catch(function() {});
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "试验、计量导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      importTemplate().then((response) => {
        this.download(response.msg);
      });
    },
     // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(response.msg, "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    /** 完好状态修改 */
    handleChangeState(row) {
      const equipmentIds = row.equipmentId || this.ids;
      this.$confirm('是否确认修改试验设备\计量设备信息状态为完好', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return changeState(equipmentIds,0);
        }).then(() => {
          this.getList();
          this.msgSuccess("提交成功");
        }).catch(function() {});
    },
    //禁用
    handleChangeForbidState(row){
      const equipmentIds = row.equipmentId || this.ids;
      this.$confirm('是否确认修改试验设备\计量设备信息状态为禁用', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return changeState(equipmentIds,2);
        }).then(() => {
          this.getList();
          this.msgSuccess("提交成功");
        }).catch(function() {});
    },
    //维修
    handleChangeRepairState(row){
      this.reset();
      const equipmentIds = row.equipmentId || this.ids;
      this.repair.form.relIds = equipmentIds;
      this.repair.open = true;
      this.title = "维修";
    },
    //提交维修信息
    submitRepairForm(){
        this.$refs["repairForm"].validate(valid => {
          if (valid) {
              addRepair(this.addMyDateRange(this.repair.form, this.repair.form.repairDaterange)).then(response => {
                if (response.code === 200) {
                  this.msgSuccess("新增成功");
                  this.repair.open = false;
                  this.getList();
                }
              });
          }
        });
    },
    //修改列颜色
    tableRowClassName({row, rowIndex}) {
        if (row.useState === 0) {
          return 'success-row';
        } else if (row.useState === 1) {
          return 'warning-row';
        } else if (row.useState === 2) {
          return 'danger-row';
        }
        return '';
    },
    //维修工单详情
    handleRepairDetail(row){
      this.repairDetail.queryParams.relId = row.equipmentId;
      this.repairDetail.queryParams.tableName = "0";
      listRepair(this.repairDetail.queryParams).then(response => {
        this.repairDetail.repairList = response.rows;
      });
      this.repairDetail.open = true;
      this.title = "维修详情";
    }
  }
};
</script>
<style scoped>
  .el-table .warning-row {
    background: rgb(248, 226, 186);
  }

  .el-table .success-row {
    background: #ffffff;
  }

  .el-table .danger-row {
    background: #f5b38d;
  }
</style>